package com.lagou.rpc.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * bytebuf转json
 */
public class RpcDecoder extends ByteToMessageDecoder {

    Serializer serializer;
    Class targetClass;
    public RpcDecoder(Serializer serializer, Class targetClass) {
        this.serializer = serializer;
        this.targetClass = targetClass;
    }
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf buf, List<Object> list) throws Exception {
        int length = buf.readInt();
        byte[] arr = new byte[length];
        buf.readBytes(arr);
        Object req = serializer.deserialize(targetClass, arr);
        list.add(req);
    }
}
